#include "mytcpserver.h"
#include <QThread>
#include "mytcpsocket.h"
#include "mytcpsockettodevice.h"
#include "mytcpsockettouser.h"

MyTcpServer::MyTcpServer(MyTcpServer::ServerType type, QObject *parent)
    : QTcpServer{parent}
    , serverType(type)
{

}

void MyTcpServer::serverCloseAndClear()
{
    if(this->isListening())
        this->close();
    emit abortAllClient();
}

void MyTcpServer::socketDisconnectedSlot()
{
    MyTcpSocket *socket = qobject_cast<MyTcpSocket *>(sender());
    disconnect(socket, nullptr, nullptr, nullptr);
    disconnect(this, nullptr, socket, nullptr);
    socket->deleteLater();
    socket->thread()->exit();
}

void MyTcpServer::incomingConnection(qintptr socketDescriptor)
{
    autoFreeThread();

    MyTcpSocket *socket;

    if(serverType == MyTcpServer::DeviceServer)
    {
        socket = new MyTcpSocketToDevice;
    }
    else
    {
        socket = new MyTcpSocketToUser;
    }

    socket->setSocketDescriptor(socketDescriptor);

    connect(socket, &MyTcpSocket::disconnected,
            this, &MyTcpServer::socketDisconnectedSlot);
    connect(this, &MyTcpServer::abortAllClient,
            socket, &MyTcpSocket::myAbortSlot);
    //send   socket->server
    connect(socket, &MyTcpSocket::dataSendSig,
            this, &MyTcpServer::dataSendSig);
    //receive  server->socket
    connect(this, &MyTcpServer::dataReceiveSig,
            socket, &MyTcpSocket::dataReceiveSig);
    connect(socket, &MyTcpSocket::sendDataToAllSig,
            this, &MyTcpServer::dataReceiveSig);

    QThread *th = new QThread;
    th->start();
    socket->moveToThread(th);
    thList.append(th);
}

void MyTcpServer::autoFreeThread()
{
    for(int i = 0; i < thList.length(); i++)
    {
        if(thList.at(i)->isFinished())
        {
            QThread * th = thList.at(i);
            thList.removeAt(i);
            th->deleteLater();
        }
    }
}
